//
// Created by 27411 on 2025/11/8.
//
#include "student/order.h"




int create_order(int student_id) {

    frontuser* student = find_student_by_id(student_id);
    if (student == NULL) {
        printf("错误：未找到ID为 %d 的学生！\n", student_id);
        return -1;
    }

    printf("\n欢迎，%s（学号：%s）！您的余额为: %s 元\n",
           student->username, student->number, student->balance);
    display_menu(); // 这个函数需要从数据库加载或访问全局数组

    Order new_order = {0};
//    // 注意：订单ID现在由数据库自动生成，这里可以先设为0
    new_order.student_id = student_id;

    // ... [前面的点餐逻辑保持不变] ...
    char choice;
    do {
        int menu_id, quantity;
        printf("\n请输入您要点的菜品ID (输入0结束点餐): ");
        scanf("%d", &menu_id);
        if (menu_id == 0) break;

        Menu* item = find_menu_item_by_id(menu_id); // 同样，需要数据来源
        if (item == NULL) { printf("错误：没有这个菜品ID！\n"); continue; }

        printf("请输入购买数量: ");
        scanf("%d", &quantity);
        if (quantity <= 0 || quantity > item->menu_number) {
            printf("错误：数量无效或库存不足！\n"); continue;
        }

        new_order.items[new_order.item_count].menu_id = menu_id;
        new_order.items[new_order.item_count].quantity = quantity;
        new_order.items[new_order.item_count].unit_price = item->menu_money;
        new_order.item_count++;
        new_order.total_amount += item->menu_money * quantity;

        printf("已添加 \"%s\" x %d 到订单。\n", item->menu_name, quantity);
    } while (1);

    if (new_order.item_count == 0) {
        printf("您没有点任何菜品，订单已取消。\n");
        return -1;
    }

    float student_balance = atof(student->balance);
    if (new_order.total_amount > student_balance) {
        printf("\n错误：您的余额不足！\n");
        printf("订单总金额: %d 元，您的余额: %s 元\n", new_order.total_amount, student->balance);
        return -1;
    }

    // --- 核心改动：开始数据库事务 ---
    sqlite3_exec(db, "BEGIN TRANSACTION;", NULL, NULL, NULL);

    // 1. 插入订单主表和明细表，并获取数据库生成的 order_id
    if (db_insert_order(&new_order) != 0) {
        sqlite3_exec(db, "ROLLBACK;", NULL, NULL, NULL);
        printf("订单创建失败：数据库插入错误。\n");
        return -1;
    }

    // 2. 更新学生余额
    float new_balance = student_balance - new_order.total_amount;
    if (db_update_student_balance(student_id, new_balance) != 0) {
        sqlite3_exec(db, "ROLLBACK;", NULL, NULL, NULL);
        printf("订单创建失败：更新余额错误。\n");
        return -1;
    }
    // 同时更新内存中的学生信息
    sprintf(student->balance, "%.0f", new_balance);

    // 3. 更新菜品库存
    for (int i = 0; i < new_order.item_count; i++) {
        Menu* item = find_menu_item_by_id(new_order.items[i].menu_id);
        if (item) {
            int new_stock = item->menu_number - new_order.items[i].quantity;
            if (db_update_menu_stock(item->id, new_stock) != 0) {
                sqlite3_exec(db, "ROLLBACK;", NULL, NULL, NULL);
                printf("订单创建失败：更新库存错误。\n");
                return -1;
            }
            // 同时更新内存中的菜单信息
            item->menu_number = new_stock;
        }
    }

    // --- 提交事务 ---
    sqlite3_exec(db, "COMMIT;", NULL, NULL, NULL);


    printf("\n订单创建成功！正在处理支付...\n");
    printf("支付成功！您的新余额为: %s 元\n", student->balance);
    printf("订单ID: %d\n", new_order.id); // new_order.id 已被 db_insert_order 函数填充
    return new_order.id;
}


int db_insert_order(const Order* new_order) {
    // 1. 插入订单主表
    const char *sql_main = "INSERT INTO canteen_order_main (stu_user_id, total_amount) VALUES (?, ?);";
    sqlite3_stmt *stmt_main;
    int rc = sqlite3_prepare_v2(db, sql_main, -1, &stmt_main, NULL);
    if (rc != SQLITE_OK) {
        fprintf(stderr, "预编译订单主表插入SQL出错: %s\n", sqlite3_errmsg(db));
        return -1;
    }

    sqlite3_bind_int(stmt_main, 1, new_order->student_id);
    sqlite3_bind_int(stmt_main, 2, new_order->total_amount);

    rc = sqlite3_step(stmt_main);
    if (rc != SQLITE_DONE) {
        fprintf(stderr, "插入订单主表失败: %s\n", sqlite3_errmsg(db));
        sqlite3_finalize(stmt_main);
        return -1;
    }

    // 获取刚刚插入的订单ID
    int order_id = sqlite3_last_insert_rowid(db);
    sqlite3_finalize(stmt_main);

    // 2. 插入订单项明细表
    const char *sql_item = "INSERT INTO canteen_order_item (order_id, canteen_menu_id, quantity, unit_price) VALUES (?, ?, ?, ?);";
    sqlite3_stmt *stmt_item;
    rc = sqlite3_prepare_v2(db, sql_item, -1, &stmt_item, NULL);
    if (rc != SQLITE_OK) {
        fprintf(stderr, "预编译订单项明细表插入SQL出错: %s\n", sqlite3_errmsg(db));
        return -1;
    }

    for (int i = 0; i < new_order->item_count; i++) {
        const OrderItem* item = &new_order->items[i];

        sqlite3_bind_int(stmt_item, 1, order_id);
        sqlite3_bind_int(stmt_item, 2, item->menu_id);
        sqlite3_bind_int(stmt_item, 3, item->quantity);
        sqlite3_bind_int(stmt_item, 4, item->unit_price);

        rc = sqlite3_step(stmt_item);
        if (rc != SQLITE_DONE) {
            fprintf(stderr, "插入订单项失败: %s\n", sqlite3_errmsg(db));
            sqlite3_finalize(stmt_item);
            return -1;
        }
        sqlite3_reset(stmt_item);
    }

    sqlite3_finalize(stmt_item);

    // 将数据库生成的ID回填到订单结构体中
    // 注意：这需要 new_order 指针指向的结构体是非 const 的，或者在调用前处理
    // 这里为了演示，我们假设可以修改。如果不行，可以返回 order_id。
    ((Order*)new_order)->id = order_id;

    printf("订单数据已成功插入数据库。\n");
    return 0;
}


int db_update_student_balance(int student_id, float new_balance) {
    char sql[100];
    sprintf(sql, "UPDATE stu_user SET balance = '%.0f' WHERE id = %d;", new_balance, student_id);

    char *err_msg = NULL;
    int rc = sqlite3_exec(db, sql, NULL, NULL, &err_msg);
    if (rc != SQLITE_OK) {
        fprintf(stderr, "更新学生余额失败: %s\n", err_msg);
        sqlite3_free(err_msg);
        return -1;
    }
    return 0;
}

int db_update_menu_stock(int menu_id, int new_stock) {
    char sql[100];
    sprintf(sql, "UPDATE canteen_menu SET menu_number = %d WHERE id = %d;", new_stock, menu_id);

    char *err_msg = NULL;
    int rc = sqlite3_exec(db, sql, NULL, NULL, &err_msg);
    if (rc != SQLITE_OK) {
        fprintf(stderr, "更新菜品库存失败: %s\n", err_msg);
        sqlite3_free(err_msg);
        return -1;
    }
    return 0;
}

void order_user_query(int order_id) {
    // 注意：这里的查询逻辑应该根据订单ID来查，而不是学生ID
    // 为了获取完整信息，需要关联4个表
    const char *sql =
            "SELECT "
            "   m.order_id, "
            "   u.username, "
            "   u.number AS student_number, "
            "   mi.menu_name, "
            "   i.quantity, "
            "   i.unit_price, "
            "   m.total_amount "
            "FROM "
            "   canteen_order_main m "
            "JOIN "
            "   stu_user u ON m.stu_user_id = u.id "
            "JOIN "
            "   canteen_order_item i ON m.order_id = i.order_id "
            "JOIN "
            "   canteen_menu mi ON i.canteen_menu_id = mi.id "
            "WHERE "
            "   m.order_id = ?;";

    sqlite3_stmt *stmt;
    int rc = sqlite3_prepare_v2(db, sql, -1, &stmt, NULL);
    if (rc != SQLITE_OK) {
        fprintf(stderr, "预编译查询SQL出错: %s\n", sqlite3_errmsg(db));
        return;
    }

    sqlite3_bind_int(stmt, 1, order_id);

    printf("\n=========================================\n");
    printf("             订单详情 (ID: %d)\n", order_id);
    printf("=========================================\n");
    int first_row = 1;
    double total_amount = 0.0;
    while (sqlite3_step(stmt) == SQLITE_ROW) {
        if (first_row) {
            // 只在第一行打印一次订单头信息
            printf("订单ID: %d\n", sqlite3_column_int(stmt, 0));
            printf("下单人: %s (学号: %s)\n",
                   (const char *) sqlite3_column_text(stmt, 1),
                   (const char *) sqlite3_column_text(stmt, 2));
            printf("-----------------------------------------\n");
            printf("订单ID|菜品名称       | 数量 | 单价 (元)\n");
            printf("-----------------------------------------\n");

            // 从第一行获取总金额
            total_amount = sqlite3_column_double(stmt, 6);

            first_row = 0;
        }

        // 打印当前行的菜品信息
        printf("%d|%-15s | %-4d | %-10d\n",
               sqlite3_column_int(stmt,0),
               (const char *) sqlite3_column_text(stmt, 3),
               sqlite3_column_int(stmt, 4),
               sqlite3_column_int(stmt, 5));
    } // while 循环结束，说明所有行都已处理完毕

    if (first_row) { // 如果循环一次都没进，说明没有找到订单
        printf("未找到订单ID: %d\n", order_id);
    } else {
        // 在循环结束后，统一打印总金额等汇总信息
        printf("-----------------------------------------\n");
        printf("订单总金额: %.2f 元\n", total_amount); // 使用之前保存的 total_amount
        printf("支付方式: 余额支付\n");
    }

    printf("=========================================\n");

    sqlite3_finalize(stmt); // 释放语句句柄
    }


void ALL_orders(sqlite3_stmt *stmt) {
    printf("\n=========================================\n");
    printf("             所有订单详情\n");
    printf("=========================================\n");

    int current_order_id = -1;
    double total_amount = 0.0;
    int order_count = 0;

    // 循环遍历结果集
    while (sqlite3_step(stmt) == SQLITE_ROW) {
        int fetched_order_id = sqlite3_column_int(stmt, 0);

        if (fetched_order_id != current_order_id) {
            // 如果不是第一个订单，打印上一个订单的尾部
            if (current_order_id != -1) {
                printf("-----------------------------------------\n");
                printf("订单总金额: %.2f 元\n", total_amount);
                printf("支付方式: 余额支付\n");
                printf("=========================================\n");
            }

            // 打印新订单的头部
            printf("订单ID: %d\n", fetched_order_id);
            printf("下单人: %s (学号: %s)\n",
                   (const char *) sqlite3_column_text(stmt, 1),
                   (const char *) sqlite3_column_text(stmt, 2));
            printf("-----------------------------------------\n");
            printf("订单ID|菜品名称       | 数量 | 单价 (元)\n");
            printf("-----------------------------------------\n");

            // 更新状态变量
            current_order_id = fetched_order_id;
            total_amount = sqlite3_column_double(stmt, 6);
            order_count++;
        }

        // 打印当前订单项
        printf("%d|%-15s | %-4d | %-10.2f\n",
               sqlite3_column_int(stmt,0),
               (const char *) sqlite3_column_text(stmt, 3),
               sqlite3_column_int(stmt, 4),
               sqlite3_column_double(stmt, 5));
    }

    // 打印最后一个订单的尾部
    if (current_order_id != -1) {
        printf("-----------------------------------------\n");
        printf("订单总金额: %.2f 元\n", total_amount);
        printf("支付方式: 余额支付\n");
        printf("=========================================\n");
    }

    // 打印总结信息
    if (order_count == 0) {
        printf("数据库中没有找到任何订单。\n");
    } else {
        printf("查询完成，共找到 %d 个订单。\n", order_count);
    }

    printf("=========================================\n");
}

void query_all_orders() {
    // 查询所有订单，关联4个表以获取完整信息
    const char *sql =
            "SELECT "
            "   m.order_id, "
            "   u.username, "
            "   u.number AS student_number, "
            "   mi.menu_name, "
            "   i.quantity, "
            "   i.unit_price, "
            "   m.total_amount "
            "FROM "
            "   canteen_order_main m "
            "JOIN "
            "   stu_user u ON m.stu_user_id = u.id "
            "JOIN "
            "   canteen_order_item i ON m.order_id = i.order_id "
            "JOIN "
            "   canteen_menu mi ON i.canteen_menu_id = mi.id "
            "ORDER BY "
            "   m.order_id asc;";

    sqlite3_stmt *stmt;
    int rc = sqlite3_prepare_v2(db, sql, -1, &stmt, NULL);
    if (rc != SQLITE_OK) {
        fprintf(stderr, "预编译查询所有订单SQL出错: %s\n", sqlite3_errmsg(db));
        return;
    }

    // 调用新的UI函数来显示结果
    ALL_orders(stmt);

    // 清理语句句柄
    sqlite3_finalize(stmt);
}

    static int g_last_order_id = -1;

    void start_order_process() {
        int student_id;
        printf("\n=====================================\n");
        printf("           开始点餐\n");
        printf("=====================================\n");
        printf("请输入您的学生ID: ");
        scanf("%d", &student_id);

        // 调用订单创建逻辑，返回订单ID
        int new_order_id = create_order(student_id);

        // 更新最近订单ID（创建成功则存储，失败则清空）
        g_last_order_id = (new_order_id != -1) ? new_order_id : -1;

        if (new_order_id == -1) {
            printf("点餐流程终止！\n");
        } else {
            printf("点餐完成！\n");
        }
    }

    void settle_and_view_order() {
        printf("\n=====================================\n");
        printf("           结算并查看订单\n");
        printf("=====================================\n");

        if (g_last_order_id != -1) {
            printf("正在加载最新订单详情...\n");
            order_user_query(g_last_order_id); // 查看订单
            printf("结算完成！\n");
            g_last_order_id = -1; // 结算后清空，避免重复查看
        } else {
            printf("❌ 无待结算订单！\n");
            printf("请先通过 [2. 开始点餐] 创建订单\n");
        }
    }


    void view_history_order() {
        printf("\n=====================================\n");
        printf("           查看历史订单\n");
        printf("=====================================\n");

        int order_id;
        printf("请输入要查询的订单ID: ");
        scanf("%d", &order_id);

        printf("正在查询订单ID: %d...\n", order_id);
        order_user_query(order_id);
    }


    int get_last_order_id() {
        return g_last_order_id;
    }

    void reset_last_order_id() {
        g_last_order_id = -1;
    }
